package com.cxd.base.controller;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.cxd.base.common.exception.CxdException;
import com.cxd.base.util.BeanTools;
import com.cxd.base.util.ProjecConfig;
import com.cxd.base.util.SequenceManager;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

/**
 * <一句话功能简述> <功能详细描述>
 * @author wtj
 * @date 2015年12月1日 下午4:16:20
 * @company CXD
 * @version [Copyright (c) 2015 V001]
 */
public class BaseController {
	
	protected Logger logger = Logger.getLogger(this.getClass());

	@Resource
	public BeanTools db;
	
	private static Configuration config = null;

	
	/**
	 * 得到request对象
	 */
	public HttpServletRequest getRequest() {
		HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
		return request;
	}
	protected String getParam(String name, String defined) {
		HttpServletRequest request = this.getRequest();
		return request.getParameter(name) == null || request.getParameter(name).equals("") ? defined : request.getParameter(name).trim();
	}
	protected String getParam(String name,HttpServletRequest request) {
		return request.getParameter(name).trim();
	}

	protected Integer getParam(String name, int defined) {
		HttpServletRequest request = this.getRequest();
		return request.getParameter(name) == null || request.getParameter(name).equals("") ? new Integer(defined) : new Integer(request.getParameter(name));
	}

	protected Long getParam(String name, long defined) {
		HttpServletRequest request = this.getRequest();
		return request.getParameter(name) == null || request.getParameter(name).equals("") ? new Long(defined) : new Long(request.getParameter(name));
	}

	protected Float getParam(String name, float defined) {
		HttpServletRequest request = this.getRequest();
		return request.getParameter(name) == null || request.getParameter(name).equals("") ? new Float(defined) : new Float(request.getParameter(name));
	}

	protected Double getParam(String name, double defined) {
		HttpServletRequest request = this.getRequest();
		return request.getParameter(name) == null || request.getParameter(name).equals("") ? new Double(defined) : new Float(request.getParameter(name));
	}
	
	
	protected void jsonMsg(JSONObject json, int f, String trueMsg) {
		json.put("status", f);
		json.put("msg", trueMsg);
	}
	
	protected void jsonMsg(JSONObject json, int f, String trueMsg, String falseMsg) {
		json.put("status", f);
		if (f==200) {
			json.put("msg", trueMsg);
		} else {
			json.put("msg", falseMsg);
		}
	}
	
	protected void jsonException(JSONObject json,Exception e,Logger logger){
		e.printStackTrace();
		String ec = SequenceManager.getNextId();
		json.put("status", 404);
		json.put("msg", "出现异常，请联系管理员:"+ec);
		logger.error("异常编号:"+ec, e);
	}
	/**
	 * 自定义异常信息输出
	 * <一句话功能简述>
	 * <功能详细描述>
	 * @author WTJ
	 * @date 2015-5-20 上午8:32:12 
	 * @param json
	 * @param e
	 * @see [类、类#方法、类#成员]
	 */
	protected void cxdJsonException(JSONObject json,CxdException e,String value){
		json.put("status", 500);
		json.put("msg", e.getMessage());
		logger.debug("-- 500 --访问参数:"+value+e.getMessage(),e);
	}
	
	protected void mapException(Map<String, Object> root,Exception e,Logger logger){
		String ec = SequenceManager.getNextId();
		root.put("success", false);
		root.put("msg", "出现异常，请联系管理员:"+ec);
		logger.error("异常编号:"+ec, e);
	}
	
	/**
	 * 自定义异常信息提示
	 * <一句话功能简述>
	 * <功能详细描述>
	 * @author WTJ
	 * @date 2015-5-20 上午8:32:33 
	 * @param root
	 * @param e
	 * @see [类、类#方法、类#成员]
	 */
	protected void cxdMapException(Map<String, Object> root,CxdException e){
		root.put("status", false);
		root.put("msg", e.getMessage());
	}
	protected boolean responseSendMsg(HttpServletResponse response, String strMsg,
			String... contentType) throws IOException {
		try {
			if (null != contentType && contentType.length > 0) {
				response.setContentType(contentType[0] + "; charset=utf-8");
			} else {
				response.setContentType("application/json; charset=utf-8");
			}
			response.setCharacterEncoding("utf-8");
			response.getWriter().write(strMsg);
			response.getWriter().flush();
			response.getWriter().close();
		} catch (Exception e) {
			logger.error("responseSendMsg出现异常,异常信息:" + e.toString());
		}
		return false;
	}
	
	protected boolean responseSendMsg(Long beginTime ,HttpServletResponse response, String strMsg,
			String... contentType) throws IOException {
		try {
			if (null != contentType && contentType.length > 0) {
				response.setContentType(contentType[0] + "; charset=utf-8");
			} else {
				response.setContentType("application/json; charset=utf-8");
			}
			logger.info("处理时长:"+(System.currentTimeMillis()-beginTime));
			logger.info("返回数据大小:"+bytes2kb(strMsg.getBytes().length));
			response.setCharacterEncoding("utf-8");
			response.getWriter().write(strMsg);
			response.getWriter().flush();
			response.getWriter().close();
		} catch (Exception e) {
			logger.error("responseSendMsg出现异常,异常信息:" + e.toString());
		}
		return false;
	}
    /** 
     * byte(字节)根据长度转成kb(千字节)和mb(兆字节) 
     *  
     * @param bytes 
     * @return 
     */  
    public static String bytes2kb(long bytes) {  
        BigDecimal filesize = new BigDecimal(bytes);
        float returnValue = 0f;
//        BigDecimal megabyte = new BigDecimal(1024 * 1024);  
//        float returnValue = filesize.divide(megabyte, 2, BigDecimal.ROUND_UP).floatValue();  
//        if (returnValue > 1)  
//            return (returnValue + "MB");  
        BigDecimal kilobyte = new BigDecimal(1024);  
        returnValue = filesize.divide(kilobyte, 2, BigDecimal.ROUND_UP).floatValue();  
        return (returnValue + "KB");  
    }  
	/**
	 * <一句话功能简述> <功能详细描述>
	 * 
	 * @author wtj
	 * @date 2013-10-8 上午11:28:35
	 * @param response
	 * @param strMsg
	 * @param contentType
	 * @throws IOException
	 * @see [类、类#方法、类#成员]
	 * 
	 * json 时间格式化
	 * JSON.toJSONStringWithDateFormat(json, "yyyy-MM-dd", SerializerFeature.WriteDateUseDateFormat)
	 */
	protected boolean responseSendMsg(HttpServletResponse response, JSONObject strMsg,
			String... contentType) throws IOException {
		try {
			if (null != contentType && contentType.length > 0) {
				response.setContentType(contentType[0] + "; charset=utf-8");
			} else {
				response.setContentType("application/json; charset=utf-8");
			}
			response.setCharacterEncoding("utf-8");
			response.getWriter().write(JSONObject.toJSONString(strMsg,SerializerFeature.WriteMapNullValue));
			response.getWriter().flush();
			response.getWriter().close();
		} catch (Exception e) {
			logger.error("responseSendMsg出现异常,异常信息:" + e.toString());
		}
		return false;
	}
	@SuppressWarnings("deprecation") 
	public void writeTemplate(HttpServletResponse response, Map<String, Object> param, String templateName) {
		try {
			if (null == config) {
				config = new Configuration();
			}
			param.put("webRoot", ProjecConfig.WEB_ROOT);
			config.setDirectoryForTemplateLoading(new File(ProjecConfig.BASE_FIlE_PATH+"views/"));
			config.setClassicCompatible(true);
			config.setDefaultEncoding("UTF-8");
			config.setTagSyntax(Configuration.AUTO_DETECT_TAG_SYNTAX);
			PrintWriter out = response.getWriter();
			Template template = config.getTemplate(templateName);
			template.setEncoding("UTF-8");
			response.setContentType("text/html; charset=" + template.getEncoding());
			template.process(param, out);
			template.setAutoFlush(true);
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (TemplateException e) {
			e.printStackTrace();
		}
	}
	public void requestLog(String key,String value){
		logger.error("接口请求【"+key+"】"+value);
	}
}
